package com.lanou.connotationjoke.adapter;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.android.volley.toolbox.NetworkImageView;
import com.lanou.connotationjoke.R;
import com.lanou.connotationjoke.activity.WebViewActivity;
import com.lanou.connotationjoke.db.HomeCollectEntity;
import com.lanou.connotationjoke.db.HomeCollectEntityDao;
import com.lanou.connotationjoke.entity.DataDetialEty;
import com.lanou.connotationjoke.entity.JsonEty;
import com.lanou.connotationjoke.tool.DaoSingleton;
import com.lanou.connotationjoke.tool.MyAppllication;
import com.lanou.connotationjoke.tool.ShareSingleton;
import com.lanou.connotationjoke.tool.VolleySingleton;

import java.util.List;

/**
 * Created by dllo on 16/1/14.
 */
public class HomeVideoListViewAdapter extends BaseAdapter {
    private Context context;
    private List<DataDetialEty> datas;
    private HomeCollectEntityDao homeCollectEntityDao
            = DaoSingleton.getInstance().getHomeCollectEntityDao();
    public HomeVideoListViewAdapter(Context context, List<DataDetialEty> datas) {
        this.context = context;
        this.datas = datas;
    }

    @Override
    public int getCount() {
        return datas.size();
    }

    @Override
    public Object getItem(int position) {
        return datas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        if (datas.get(position).getGroup() != null) {
            VideoViewHolder videoViewHolder = null;
            VideoWithCommentViewHolder commentViewHolder = null;
            int type = getItemViewType(position);
            if (convertView == null) {
                if (type == 0) {
                    convertView = LayoutInflater.from(context).inflate(R.layout.item_listview_home_video_test, null);
                    videoViewHolder = new VideoViewHolder(convertView);
                    convertView.setTag(videoViewHolder);
                } else {
                    convertView = LayoutInflater.from(context).inflate(R.layout.item_listview_home_video_comment, null);
                    commentViewHolder = new VideoWithCommentViewHolder(convertView);
                    convertView.setTag(commentViewHolder);
                }
            } else {
                if (type == 0) {
                    //TODO 没解决将videoViewHolder中coverImageIv单独初始化,目前只能将videoViewHolder
                    //TODO 通过构造方法全部初始化,这样使得convertView没得到复用效率降低
                    convertView = LayoutInflater.from(context).inflate(R.layout.item_listview_home_video, null);
                    videoViewHolder = new VideoViewHolder(convertView);
                } else {
                    convertView = LayoutInflater.from(context).inflate(R.layout.item_listview_home_video_comment, null);
                    commentViewHolder = new VideoWithCommentViewHolder(convertView);
                }
            }
            if (type == 0) {
                videoViewHolder.playCountTv.setText(""+datas.get(position).getGroup().getPlay_count());
                videoViewHolder.diggTv.setText("" + datas.get(position).getGroup().getDigg_count());
                videoViewHolder.contentTv.setText(datas.get(position).getGroup().getContent());
                videoViewHolder.userNameTv.setText(datas.get(position).getGroup().getUser().getName());
                videoViewHolder.categoryNameTv.setText(datas.get(position).getGroup().getCategory_name());
                videoViewHolder.buryTv.setText("" + datas.get(position).getGroup().getBury_count());
                videoViewHolder.hotCommentTv.setText("" + datas.get(position).getGroup().getComment_count());
                videoViewHolder.sendTv.setText("" + datas.get(position).getGroup().getShare_count());
                videoViewHolder.userPictureIv.setDefaultImageResId(R.mipmap.ic_launcher);
                videoViewHolder.userPictureIv.setErrorImageResId(R.mipmap.ic_launcher);
                videoViewHolder.userPictureIv.setImageUrl(datas.get(position).getGroup().getUser().getAvatar_url()
                        , VolleySingleton.getImageLoader());
                videoViewHolder.coverImageIv.setDefaultImageResId(R.mipmap.ic_launcher);
                videoViewHolder.coverImageIv.setErrorImageResId(R.mipmap.ic_launcher);
                videoViewHolder.coverImageIv.setImageUrl(datas.get(position).getGroup().getCover_image_uri(),
                        VolleySingleton.getImageLoader());
                final VideoViewHolder finalVideoViewHolder = videoViewHolder;
                videoViewHolder.coverImageIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (MyAppllication.hasNetwork()){
                            finalVideoViewHolder.playVideoIv.setVisibility(View.GONE);
                            finalVideoViewHolder.progressBar.setVisibility(View.VISIBLE);
                            finalVideoViewHolder.videoView.setVideoURI(Uri.parse(datas.get(position).getGroup().getMp4_url()));
                            finalVideoViewHolder.videoView.setMediaController(new MediaController(context));

                            finalVideoViewHolder.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mp) {
                                    Toast.makeText(context, "播放完成", Toast.LENGTH_SHORT).show();
                                }
                            });

                            finalVideoViewHolder.videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                                @Override
                                public boolean onError(MediaPlayer mp, int what, int extra) {
                                    Toast.makeText(context, "很抱歉,播放失败了", Toast.LENGTH_SHORT).show();
                                    return true;
                                }
                            });
                            finalVideoViewHolder.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    Toast.makeText(context, "准备播放", Toast.LENGTH_SHORT).show();
                                    finalVideoViewHolder.frameLayout.setVisibility(View.GONE);
                                    finalVideoViewHolder.videoView.requestFocus();
                                    finalVideoViewHolder.videoView.start();
                                }
                            });
                        }else {
                            Toast.makeText(context, "没有网络", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                videoViewHolder.contentTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (MyAppllication.hasNetwork()){
                            final String url = "http://neihanshequ.com/p"+datas.get(position).getGroup().getShare_url().substring(37);
                            WebViewActivity.goToWebViewActivity(context, url);
                        }else {
                            Toast.makeText(context, "没有网络", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                videoViewHolder.shareIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (MyAppllication.hasNetwork()){
                            String title = "超级搞笑";
                            String titleurl = "http://neihanshequ.com/p" + datas.get(position).getGroup().getShare_url().substring(37);
                            String content = datas.get(position).getGroup().getContent();
                            String imageurl = datas.get(position).getGroup().getUser().getAvatar_url();
                            ShareSingleton.getInstance().shareOnQQ(title, titleurl, content, imageurl);
                        }else {
                            Toast.makeText(context, "分享失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                videoViewHolder.collectTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        insertDataToHomeCollectDao(datas.get(position));
                        Toast.makeText(context, "收藏成功", Toast.LENGTH_SHORT).show();
                    }
                });


            } else {
                commentViewHolder.playCountTv.setText(""+datas.get(position).getGroup().getPlay_count());
                commentViewHolder.userNameTv.setText(datas.get(position).getGroup().getUser().getName());
                commentViewHolder.contentTv.setText(datas.get(position).getGroup().getContent());
                commentViewHolder.categoryNameTv.setText(datas.get(position).getGroup().getCategory_name());
                commentViewHolder.diggTv.setText("" + datas.get(position).getGroup().getDigg_count());
                commentViewHolder.buryTv.setText("" + datas.get(position).getGroup().getBury_count());
                commentViewHolder.hotCommentTv.setText("" + datas.get(position).getGroup().getComment_count());
                commentViewHolder.sendTv.setText("" + datas.get(position).getGroup().getShare_count());
                commentViewHolder.userPictureIv.setDefaultImageResId(R.mipmap.ic_launcher);
                commentViewHolder.userPictureIv.setErrorImageResId(R.mipmap.ic_launcher);
                commentViewHolder.userPictureIv.setImageUrl(datas.get(position).getGroup().getUser().getAvatar_url()
                        , VolleySingleton.getImageLoader());
                commentViewHolder.commentUserNameTv.setText(datas.get(position).getComments().get(0).getUser_name());
                commentViewHolder.commentDiggCountTv.setText("" + datas.get(position).getComments().get(0).getDigg_count());
                commentViewHolder.commentContentTv.setText("" + datas.get(position).getComments().get(0).getText());
                commentViewHolder.commentUserPictureIv.setDefaultImageResId(R.mipmap.ic_launcher);
                commentViewHolder.commentUserPictureIv.setErrorImageResId(R.mipmap.ic_launcher);
                commentViewHolder.commentUserPictureIv.setImageUrl(datas.get(position).getComments().get(0).getAvatar_url(),
                        VolleySingleton.getImageLoader());
                commentViewHolder.coverImageIv.setDefaultImageResId(R.mipmap.ic_launcher);
                commentViewHolder.coverImageIv.setErrorImageResId(R.mipmap.ic_launcher);
                commentViewHolder.coverImageIv.setImageUrl(datas.get(position).getGroup().getCover_image_uri(),
                        VolleySingleton.getImageLoader());
                final VideoWithCommentViewHolder finalCommentViewHolder = commentViewHolder;
                commentViewHolder.coverImageIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (MyAppllication.hasNetwork()){
                            finalCommentViewHolder.playVideoIv.setVisibility(View.GONE);
                            finalCommentViewHolder.progressBar.setVisibility(View.VISIBLE);
                            finalCommentViewHolder.videoView.setVideoURI(
                                    Uri.parse(datas.get(position).getGroup().getMp4_url()));
                            finalCommentViewHolder.videoView.setMediaController(new MediaController(context));
                            finalCommentViewHolder.videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                @Override
                                public void onPrepared(MediaPlayer mp) {
                                    finalCommentViewHolder.frameLayout.setVisibility(View.GONE);
                                    finalCommentViewHolder.videoView.requestFocus();
                                    finalCommentViewHolder.videoView.start();
                                }
                            });
                            finalCommentViewHolder.videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                                @Override
                                public boolean onError(MediaPlayer mp, int what, int extra) {
                                    Toast.makeText(context, "很抱歉,播放失败了", Toast.LENGTH_SHORT).show();
                                    return true;
                                }
                            });
                            finalCommentViewHolder.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mp) {
                                    Toast.makeText(context, "播放完成", Toast.LENGTH_SHORT).show();
                                }
                            });

                        }else {
                            Toast.makeText(context, "没有网络", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                commentViewHolder.contentTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (MyAppllication.hasNetwork()){
                            final String url = "http://neihanshequ.com/p"+datas.get(position).getGroup().getShare_url().substring(37);
                            WebViewActivity.goToWebViewActivity(context, url);
                        }else {
                            Toast.makeText(context, "没有网络", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

                commentViewHolder.shareIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (MyAppllication.hasNetwork()){
                            String title = "超级搞笑";
                            String titleurl = "http://neihanshequ.com/p" + datas.get(position).getGroup().getShare_url().substring(37);
                            String content = datas.get(position).getGroup().getContent();
                            String imageurl = datas.get(position).getGroup().getUser().getAvatar_url();
                            ShareSingleton.getInstance().shareOnQQ(title, titleurl, content, imageurl);
                        }else {
                            Toast.makeText(context, "分享失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                commentViewHolder.collectTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        insertDataToHomeCollectDao(datas.get(position));
                        Toast.makeText(context, "收藏成功", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
        return convertView;
    }

    @Override
    public int getItemViewType(int position) {
        if (datas.get(position).getComments() == null || datas.get(position).getComments().size() == 0) {
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }


    public void refreshData(List<DataDetialEty> datas){
        this.datas = datas;
        notifyDataSetChanged();
    }


    private void insertDataToHomeCollectDao(DataDetialEty dataDetialEty){
        String avatar_url = dataDetialEty.getGroup().getUser().getAvatar_url();
        String name = dataDetialEty.getGroup().getUser().getName();
        String content = dataDetialEty.getGroup().getContent();
        String category_name = dataDetialEty.getGroup().getCategory_name();
        int digg_count = dataDetialEty.getGroup().getDigg_count();
        int bury_count = dataDetialEty.getGroup().getBury_count();
        int comment_count = dataDetialEty.getGroup().getComment_count();
        int share_count = dataDetialEty.getGroup().getShare_count();
        String share_url = dataDetialEty.getGroup().getShare_url();

        String uri = null;

        String coverImageUri = dataDetialEty.getGroup().getCover_image_uri();
        String mp4Url = dataDetialEty.getGroup().getMp4_url();
        int playCount = dataDetialEty.getGroup().getPlay_count();


        boolean differernt = true;
        List<HomeCollectEntity> homeCollectEntities = homeCollectEntityDao.queryBuilder().list();
        if (homeCollectEntities != null){
            for (HomeCollectEntity homeCollectEntity : homeCollectEntities){
                if (homeCollectEntity.getShare_url() == share_url){
                    differernt = false;
                }
            }
        }
        if (differernt){
            homeCollectEntityDao.insert(new HomeCollectEntity(homeCollectEntityDao.count(),avatar_url,name,content
                    ,category_name,uri,coverImageUri,mp4Url,playCount,digg_count,bury_count
                    ,comment_count,share_count,share_url));
        }
    }



    class VideoViewHolder {
        NetworkImageView userPictureIv;
        TextView userNameTv;
        TextView contentTv;
        TextView categoryNameTv;
        NetworkImageView coverImageIv;
        TextView playCountTv;
        VideoView videoView;
        TextView diggTv;
        TextView buryTv;
        TextView hotCommentTv;
        TextView sendTv;
        View frameLayout;
        ImageView shareIv;
        ProgressBar progressBar;
        ImageView playVideoIv;
        TextView collectTv;
        public VideoViewHolder(View itemView) {
            userPictureIv = (NetworkImageView) itemView.findViewById(R.id.iv_user_picture);
            userNameTv = (TextView) itemView.findViewById(R.id.tv_user_name);
            contentTv = (TextView) itemView.findViewById(R.id.tv_content);
            categoryNameTv = (TextView) itemView.findViewById(R.id.tv_category_name);
            coverImageIv = (NetworkImageView) itemView.findViewById(R.id.iv_cover_image);
            playCountTv = (TextView) itemView.findViewById(R.id.tv_play_count);
            videoView = (VideoView) itemView.findViewById(R.id.video_view);
            diggTv = (TextView) itemView.findViewById(R.id.tv_digg_count);
            buryTv = (TextView) itemView.findViewById(R.id.tv_bury_count);
            hotCommentTv = (TextView) itemView.findViewById(R.id.tv_hot_comment_count);
            sendTv = (TextView) itemView.findViewById(R.id.tv_send_count);
            frameLayout = itemView.findViewById(R.id.framelayout);
            shareIv = (ImageView) itemView.findViewById(R.id.iv_share_home_video);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar_home_video);
            playVideoIv = (ImageView) itemView.findViewById(R.id.iv_video_play);
            collectTv = (TextView) itemView.findViewById(R.id.tv_collect);
        }
    }

    class VideoWithCommentViewHolder {
        NetworkImageView userPictureIv;
        TextView userNameTv;
        TextView contentTv;
        TextView categoryNameTv;
        NetworkImageView coverImageIv;
        TextView playCountTv;
        VideoView videoView;
        TextView diggTv;
        TextView buryTv;
        TextView hotCommentTv;
        TextView sendTv;
        NetworkImageView commentUserPictureIv;
        TextView commentUserNameTv;
        TextView commentDiggCountTv;
        TextView commentContentTv;
        View frameLayout;
        ImageView shareIv;
        ProgressBar progressBar;
        ImageView playVideoIv;
        TextView collectTv;
        public VideoWithCommentViewHolder(View itemView) {
            userPictureIv = (NetworkImageView) itemView.findViewById(R.id.iv_user_picture);
            userNameTv = (TextView) itemView.findViewById(R.id.tv_user_name);
            contentTv = (TextView) itemView.findViewById(R.id.tv_content);
            categoryNameTv = (TextView) itemView.findViewById(R.id.tv_category_name);
            coverImageIv = (NetworkImageView) itemView.findViewById(R.id.iv_cover_image);
            playCountTv = (TextView) itemView.findViewById(R.id.tv_play_count);
            videoView = (VideoView) itemView.findViewById(R.id.video_view);
            diggTv = (TextView) itemView.findViewById(R.id.tv_digg_count);
            buryTv = (TextView) itemView.findViewById(R.id.tv_bury_count);
            hotCommentTv = (TextView) itemView.findViewById(R.id.tv_hot_comment_count);
            sendTv = (TextView) itemView.findViewById(R.id.tv_send_count);
            commentUserPictureIv = (NetworkImageView) itemView.findViewById(R.id.iv_comment_user_picture);
            commentUserNameTv = (TextView) itemView.findViewById(R.id.tv_comment_user_name);
            commentDiggCountTv = (TextView) itemView.findViewById(R.id.tv_comment_digg_count);
            commentContentTv = (TextView) itemView.findViewById(R.id.tv_comment_content);
            frameLayout = itemView.findViewById(R.id.framelayout);
            shareIv = (ImageView) itemView.findViewById(R.id.iv_share_home_video);
            progressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar_home_video);
            playVideoIv = (ImageView) itemView.findViewById(R.id.iv_video_play);
            collectTv = (TextView) itemView.findViewById(R.id.tv_collect);
        }
    }
}
